package com.lingx.web.api.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.lingx.service.LingxService;
import com.lingx.web.api.IApi;
@Component
public class Api8010 extends AbstractApi implements IApi{
	@Resource
	private LingxService lingxService;
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Override
	public int getApiCode() {
		return 8010;
	}
	@Override
	public String getApiName() {
		return "接收远程字典";
	}
	@Override
	public Map<String, Object> api(Map<String, Object> params) {
		Map<String,Object> ret=IApi.getRetMap(1, "操作成功");
		String json=IApi.getParamString(params, "json", "");
		String secret1=IApi.getParamString(params, "secret", "");
		String enabled=this.lingxService.getConfigValue("lingx.update.enabled", "none");
		String secret2=this.lingxService.getConfigValue("lingx.update.secret", "none");
		if("true".equals(enabled)&&secret2.equals(secret1)) {
			JdbcTemplate jdbc=this.jdbcTemplate;
			Map<String,Object> map=(Map<String,Object>)JSON.parseObject(json);
			handler(map,jdbc);
		}
		return ret;
	}

	public void handler(Map<String,Object> map,JdbcTemplate jdbc) {
		List<Map<String,Object>> items=(List<Map<String,Object>>)map.get("items");
		if(jdbc.queryForObject("select count(*) from tlingx_option where id=?",Integer.class,map.get("id"))==0){
			jdbc.update("insert into tlingx_option(id,name,code,app_id,create_time) values(?,?,?,?,?)",
				map.get("id"),map.get("name"),map.get("code"),map.get("app_id"),map.get("create_time"));
		}
		for(Map<String,Object> item:items){
			if(jdbc.queryForObject("select count(*) from tlingx_optionitem where id=?",Integer.class,item.get("id"))==1){
				jdbc.update("update tlingx_optionitem set name=?,value=?,orderindex=?,enabled=? where id=?",
						item.get("name"),item.get("value"),item.get("orderindex"),item.get("enabled"),item.get("id"));
			}else{
				jdbc.update("insert into tlingx_optionitem(id,name,value,option_id,orderindex,enabled) values(?,?,?,?,?,?)",
						item.get("id"),item.get("name"),item.get("value"),item.get("option_id"),item.get("orderindex"),item.get("enabled"));
			}
			
		}
	}

}
